package com.xiyun.admin.utils.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiyun.admin.entity.Department;
import com.xiyun.admin.service.DepartmentService;
import com.xiyun.admin.utils.excel.data.ReadData;
//TODO 未作优化,查询数据库次数过多,性能可能会有额外浪费
public class ExcelListener extends AnalysisEventListener<ReadData> {

    private final DepartmentService service;
    //存放读取到的数据
    // List<ReadData> list = new ArrayList<>();

    public ExcelListener(DepartmentService service){
        this.service = service;
    }

    @Override
    public void invoke(ReadData readData, AnalysisContext analysisContext) {
        // System.out.println(readData);
        String id;
        Department column1 = existColumn1(readData);
        Department column2 = existColumn2(readData);

        if (column1 == null){
            Department department = new Department();
            department.setPid("0");
            department.setDeptName(readData.getPname());
            service.save(department);
            column1 = existColumn1(readData);
        }

        id = column1.getId();

        if (column2 == null){
            Department department = new Department();
            department.setPid(id);
            department.setDeptName(readData.getDname());
            service.save(department);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    //判断是否存在一级分类,即上级部门是否已经出现在数据库中
    private Department existColumn1(ReadData readData){
        String pname = readData.getPname();
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.eq("dept_name",pname);
        return service.getOne(wrapper);
    }
    //判断是否存在二级分类
    private Department existColumn2(ReadData readData){
        String dname = readData.getDname();
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.eq("dept_name",dname);
        return service.getOne(wrapper);
    }

}
